<template >
  <crec-dropdown placement="bottomRight" :class="[showDropdown ? 'dropdown' : 'default']">
    <span class="crec-pro-account-avatar">
      <span>{{ currentUserRange }} </span>
      <crec-icon type="down" v-if="showDropdown" />
    </span>
    <template v-slot:overlay v-if="showDropdown">
      <crec-menu class="crec-pro-drop-down menu" @click="onClick" v-model="currentOrganId">
        <crec-menu-item v-for="items in dropdownList" :key="items.organId"> {{ items.organName }} </crec-menu-item>
      </crec-menu>
    </template>
  </crec-dropdown>
</template>

<script>

export default {
  name: 'RangeDropdown',
  data () {
    return {
      // currentUserRange: window.localStorage.getItem('organName'),
      currentOrganId: [],
      currentUserRange: '',
      showDropdown: false
    }
  },
  inject: ['reload'],
  computed: {
    dropdownList () {
      return this.$store.getters.identityList
    }
  },
  mounted () {
    this.init()
  },

  methods: {
    onClick ({ key }) {
      this.currentOrganId = [key]
      const data = this.dropdownList.find(item => item.organId === key)
      this.currentUserRange = data.organName
      this.$message.success(`切换组织至 ${this.currentUserRange}`)
      this.$store.dispatch('SetCurrentOrgan', data).then(() => {
        // this.$router.push('/')
        this.reload()
      })
    },
    init () {
      console.log('init', this.dropdownList)
      this.showDropdown = Boolean(this.dropdownList.length)
      if (this.showDropdown === false) {
        this.$message.error('用户无权限')
        return false
      }
      const organId = localStorage.getItem('organId')
      if (organId) {
        this.currentOrganId = [organId]
        const data = this.dropdownList.find(item => item.organId === organId)
        this.currentUserRange = data.organName
      } else {
        this.currentOrganId = [this.dropdownList[0].organId]
        this.currentUserRange = this.dropdownList[0].organName
      }
    }

  }
}
</script>

<style lang="less" scoped>
.dropdown {
  display: inline-block;
  &:hover {
    cursor: pointer;
  }
  margin-right: 12px;
}
.default {
  display: inline-block;
  margin-right: 12px;
  &:hover {
    cursor: default;
  }
}
</style>
